package com.mobzilla.service;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;

import android.os.AsyncTask;
import android.util.Log;

import com.mobzilla.util.Lock;

/** Used to make aysnc GET requests **/
class HTTPRequestAsync extends AsyncTask<String, Void, String> {
	private String url;
	private Lock<String> lock;

	public HTTPRequestAsync(String url, Lock<String> l) {
		this.url = url;
		this.lock = l;
	}

	// String result;

	@Override
	protected void onPreExecute() {
	}

	@Override
	protected String doInBackground(String... params) {
		DefaultHttpClient client = new DefaultHttpClient();
		HttpGet getRequest = new HttpGet(url);
		try {
			HttpResponse getResponse = client.execute(getRequest);
			final int statusCode = getResponse.getStatusLine().getStatusCode();

			BufferedReader reader = new BufferedReader(new InputStreamReader(
					getResponse.getEntity().getContent(), "UTF-8"));

			lock.setData(reader.readLine());		

			if (statusCode != HttpStatus.SC_OK) {
				Log.w("Mobzilla", "Error " + statusCode + " for URL " + url);
				return null;
			}
		} catch (IOException e) {
			getRequest.abort();
			
			lock.setData(null);
			Log.w("Mobzilla", "Error for URL " + url, e);
			return null;
		}
		
		lock.setDataSet(true);

		return null;
	}
}
